package jpa.controller;

import jpa.entity.Shit;
import jpa.repository.ShitRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityLinks;
import org.springframework.hateoas.ExposesResourceFor;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by barton on 16-5-14.
 */
@RequestMapping("/shits")
@Controller
@ExposesResourceFor(Shit.class) // 启用 EntityLinks 功能
// hateoas 提供的json数据遵循HAL 超文本传输格式 :http://stateless.co/hal_specification.html
public class ShitController {
    @Autowired
    private EntityLinks entityLinks;
    @Autowired
    private ShitRepository shitRepository;

    @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public HttpEntity<Resource<Shit>> shit(@PathVariable Long id) {
        Resource<Shit> resource = new Resource<>(shitRepository.findOne(id));
        resource.add(this.entityLinks.linkToSingleResource(Shit.class, id));
        return new ResponseEntity<>(resource, HttpStatus.OK);
    }

    @GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public HttpEntity<PagedResources<Shit>> shits(Pageable pageable, PagedResourcesAssembler
            assembler) {
        Page<Shit> shits = shitRepository.findAll(pageable);
        PagedResources<Shit> resources = assembler.toResource(shits);
        return new ResponseEntity<>(resources, HttpStatus.OK);
    }

}
